'use strict';

const Controller = require('egg').Controller;
const path = require('path')

const { saveFile, readFile, delFile } = require('./../../utils/fs-extend')

class SectionController extends Controller {
  async import_sections() {
    const { ctx, service } = this
    const upload_path_id = 29
    const navJson = JSON.parse(readFile(__dirname, 'nav.json'))
    for(let nav of navJson) {
      const { serialNumber, sectionName, suffix } = nav
      const file = await service.file.create({
        upload_path_id, mime_type: 'text/markdown', filename: serialNumber+'-'+sectionName+'.'+suffix,
      })
      const section = await service.section.create({
        booklet_id: 28, serial_number: +serialNumber, file_id: file.id, name: sectionName
      })
    }
    ctx.body = navJson
  }

  //GET sections/:id
  async show() {
    const { ctx, service } = this;
    const { Response, ResponseError, query, session, params } = ctx
    const res = new Response()
    try {
      const validateRule = { user_id: 'string', nickname: 'string'}
      ctx.validate(validateRule, query)
      const { id } = params //获取信息
      const { user_id, nickname, password } = query
      if(session.user_id != user_id) { //令牌验证
        throw new ResponseError('用户没有登入')
      }
      let user = await service.user.findByFields({nickname})
      if(!user) {
        throw new ResponseError('用户：' + nickname + '不存在!')
      }

      if(user && user.status === '0') {
        throw new ResponseError('用户被锁定')
      }
      
      let section = await service.section.find(id)
      const { file_id } = section
      const file = await service.file.getFileUPath(file_id)
      const content = readFile(file.upload_path_model.value, file.filename).toString()
      section = section.toJSON()
      section.content = content
      res.data = {
        section
      }
      res.message = '获取章节成功'
    }catch(e) {
      console.log(e.message)
			res.status = ctx.STATUS.ERROR;
			res.message = e;
    }
    ctx.body = res
  }
}

module.exports = SectionController;
